<?php
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use think\facade\Console;
use app\admin\model\ArctypeLogic;
use app\common\model\Arctype as ArctypeModel;
use samdark\sitemap\Sitemap;

/////////////////////////////////////系统自定义函数区域////////////////////////
//快捷打印输出数据
if (!function_exists('_P')) 
{
    function _P($val, $stop=0, $mod=0){
        header("Content-Type:text/html; charset=utf-8");
        $mod = $mod ? 'var_dump' : 'print_r'; 
        echo '<pre>';
        $mod($val);
        echo '</pre>';
        if($stop)halt("以上是打印输出结果");
    }
}
#用于开发时生成日志用
if (!function_exists('_L')) 
{
    function _L($array, $name='ts', $mod='a'){
        if(!is_dir(WWW_ROOT.'/runtime/bug'))@mkdir(WWW_ROOT.'/runtime/bug', 0777);
        $logfile = WWW_ROOT.'/runtime/bug/~bug_'.$name.'.log';
        if(function_exists('saeAutoLoader'))return;
        if(@$fp = fopen($logfile, $mod)) {
            @fwrite($fp, date('Y-m-d H:i:s', time())."\r\n");
            @fwrite($fp, '--------------------------------------------'."\r\n");
            @fwrite($fp, var_export($array,TRUE)."\r\n");
            @fwrite($fp, '============================================'."\r\n");
            @fclose($fp);
        }
    }
}
//获取CMS版本号
if (!function_exists('getCmsVersion')) 
{
    function getCmsVersion()
    {
        $web_version = sysConfig('system.system_version');//数据库版本号
        if($web_version) {
            $ver = $web_version;
        } else {
            $ver = '未知';
        }
        return $ver;
    }
}
// 检测目录路径是否有写入权限
if (!function_exists('testWriteAble')) 
{
    function testWriteAble($filepath)
    {
        $tfile = 'session_pcfcms.txt';
        $fp = @fopen($filepath.$tfile,'w');
        if(!$fp) {
            return false;
        }else {
            fclose($fp);
            $rs = @unlink($filepath.$tfile);
            return true;
        }
    }
}
//密码生成 md5加密 
if (!function_exists('func_encrypt')) 
{
    function func_encrypt($str){
        $auth_code = "FBWQg3f7Psur9E6Usp8j";
        return md5($auth_code.$str);
    }
}
# $string：明文 或 密文
# $operation：true表示加密,false表示解密
# $key：密匙
# $outtime：密文有效期, 单位为秒
# $entype：加密方式 有md5和sha1两种 加密解密需要统一使用同一种方式才能正确还原明文
function edauth($string, $operation = true, $key = '', $outtime = 0, $entype = 'md5'){
    $key_length = 4;
    if($entype == 'md5'){ 
      $long_len = 32; $half_len = 16; $entype == 'md5';//使用md5方式
    }else{ 
      $long_len = 40; $half_len = 20; $entype == 'sha1';//使用sha1方式
    }
    $key = $key != '' ? $key : substr(md5($_SERVER['DOCUMENT_ROOT'].WWW_ROOT),0,30);
    $fixedKey = hash($entype, $key); 
    $egiskeys = md5(substr($fixedKey, $half_len, $half_len)); 
    $runtoKey = $key_length ? ($operation ? substr(hash($entype, microtime(true)), -$key_length) : substr($string, 0, $key_length)) : ''; 
    $keys = hash($entype, substr($runtoKey, 0, $half_len) . substr($fixedKey, 0, $half_len) . substr($runtoKey, $half_len) . substr($fixedKey, $half_len));
    $string = $operation ? sprintf('%010d', $outtime ? $outtime + time() : 0).substr(md5($string.$egiskeys), 0, $half_len) . $string : base64_decode(substr($string, $key_length)); 
    $i = 0; $result = ''; 
    $string_length = strlen($string);
    for ($i = 0; $i < $string_length; $i++){
        $result .= chr(ord($string{$i}) ^ ord($keys{$i % $long_len})); 
    }
    if($operation){
      return $runtoKey . str_replace('=', '', base64_encode($result));
    }else{
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, $half_len) == substr(md5(substr($result, $half_len+10).$egiskeys), 0, $half_len)) {
            return substr($result, $half_len+10);
        } else {
            return '';
        }
    }
}
// 生成全部引擎sitemap
if (!function_exists('sitemap_all')) 
{
    function sitemap_all()
    {
        $globalConfig = sysConfig('sitemap');
        if (!isset($globalConfig['sitemap_xml']) || empty($globalConfig['sitemap_xml'])) {
            return false;
        }
        if(empty(PUBLIC_ROOT)){
            $filename = WWW_ROOT."public/sitemap.xml";
        }else{
            $filename = WWW_ROOT."/sitemap.xml";
        }
        $site = new Sitemap();
        // 用于生成分类列表
        $map = [
            'status'    => 1,
            'is_hidden' => 0,
        ];
        $result_arctype = Db::name('arctype')
                        ->field("*, id AS loc, add_time AS lastmod, 'hourly' AS changefreq, '0.8' AS priority")
                        ->where($map)
                        ->order('sort_order asc, id asc')
                        ->select()->toArray();
        if(isset($result_arctype) && !empty($result_arctype))
        {
            $result_arctype = array_combine(array_column($result_arctype, 'id'), $result_arctype);
            $map = [];
            $map[] = ['channel','IN',config('pcfcms.allow_release_channel')];
            $map[] = ['arcrank','>=',0];
            $map[] = ['status','=',1];
            if (!isset($globalConfig['sitemap_archives_num']) || $globalConfig['sitemap_archives_num'] == '') {
                $sitemap_archives_num = 100;
            } else {
                $sitemap_archives_num = intval($globalConfig['sitemap_archives_num']);
            }
            $field = "aid,channel, is_jump, jumplinks, add_time, update_time, typeid, aid AS loc, add_time AS lastmod, 'daily' AS changefreq, '0.5' AS priority";
            $result1_archives = Db::name('archives')->field($field)
                              ->where($map)
                              ->order('aid desc')
                              ->limit($sitemap_archives_num)
                              ->select()->toArray();
            // 首页
            $url = request::domain();
            $site->AddItem($url,0);
            // 所有栏目
            foreach ($result_arctype as $sub){
                if ($sub['is_part'] == 1) {
                    $row1 = $sub['typelink'];
                } else {
                    $row1 = get_typeurl($sub, false);
                }
                $row1 = str_replace('&amp;', '&', $row1);
                $row1 = str_replace('&', '&amp;', $row1);
                try {
                    $site->AddItem($row1, 1);
                } catch (\Exception $e) {}
            }
            if(!empty($result1_archives)){
                $result_archives  = [];
                // 所有文档内容
                foreach ($result1_archives as $key => $val) {
                    if (is_array($val) && isset($result_arctype[$val['typeid']])) {
                       $result_archives[$key] = array_merge($result_arctype[$val['typeid']], $val);
                    }
                }            
            }
            if(isset($result_archives) && !empty($result_archives)){
                foreach ($result_archives as $key => $row) {
                    if ($row['is_jump'] == 1) {
                        $row1 = $row['jumplinks'];
                    } else {
                        $row1 = get_arcurl($row, false);
                    }
                    $row1 = str_replace('&amp;', '&', $row1);
                    $row1 = str_replace('&', '&amp;', $row1);
                    try {
                        $site->AddItem($row1, 2);
                    } catch (\Exception $e) {}
                }            
            }
            $site->SaveToFile($filename);     
        }
    }
}
//获取管理员登录信息
if (!function_exists('getAdminInfo')) 
{
    function getAdminInfo($admin_id = 0){
        $admin_info = [];
        $admin_id = empty($admin_id) ? session::get('admin_id') : $admin_id;
        if (0 < intval($admin_id)) {
            $admin_info = Db::name('admin')
                        ->field('a.*, b.name AS role_name')
                        ->alias('a')->join('auth_role b', 'b.id = a.role_id', 'LEFT')
                        ->where("a.admin_id", $admin_id)
                        ->find();
            if (!empty($admin_info)) {
                // 头像
                empty($admin_info['head_pic']) && $admin_info['head_pic'] = get_head_pic($admin_info['head_pic']);
                // 权限组
                $admin_info['role_id'] = !empty($admin_info['role_id']) ? $admin_info['role_id'] : -1;
                if ($admin_info['role_id'] == -1) {
                    if (!empty($admin_info['parent_id'])) {
                        $role_name = '超级管理员';
                    } else {
                        $role_name = '创始人';
                    }
                } else {
                    $role_name = $admin_info['role_name'];
                }
                $admin_info['role_name'] = $role_name;
            }
        }
        return $admin_info;
    }
}
// 会员获取头像，图片不存在，显示默认无图封面
if (!function_exists('get_head_pic')) 
{
    function get_head_pic($pic_url = '')
    {
        if(empty(PUBLIC_ROOT)){
           $default_pic = Request::domain().'/admin/assets/images/head.png';
        }else{
           $default_pic = Request::domain().'/'.PUBLIC_ROOT.'/admin/assets/images/head.png';
        }
        return empty($pic_url) ? $default_pic : $pic_url;
    }
}
/**
 * 图片不存在，显示默认无图封面
 * @param string $pic_url 图片路径
 * @param string|boolean $domain 完整路径的域名
 */
if (!function_exists('get_default_pic')) 
{
    function get_default_pic($pic_url = "", $domain_url = false)
    {
        if (!is_http_url($pic_url)) {
            if (true === $domain_url) {
                $domain = Request::domain();
            }else{
                $domain = "";
            }
            $pic_url = preg_replace('#^(/[/\w]+)?(/public/upload/|/uploads/)#i', '$2', $pic_url); // 支持子目录
            $realpath = realpath(trim($pic_url, '/'));
            if (is_file($realpath) && file_exists($realpath) ) {
                $pic_url = $domain.$pic_url;
            } else {
                if(empty(PUBLIC_ROOT)){
                    if (true === $domain_url){
                       $pic_url = $domain.'/common/images/not_adv.jpg';
                    }else{
                       $pic_url = '/common/images/not_adv.jpg'; 
                    }
                }else{
                    if (true === $domain_url){
                       $pic_url = $domain.'/'.PUBLIC_ROOT.'/common/images/not_adv.jpg';
                    }else{
                       $pic_url = '/'.PUBLIC_ROOT.'/common/images/not_adv.jpg';
                    } 
                }
                
            }
        }
        return $pic_url;
    }
}
/**
 * 判断url是否完整的链接
 * @param  string $url 网址
 */
if (!function_exists('is_http_url')) 
{
    function is_http_url($url)
    {
        preg_match("/^((\w)*:)?(\/\/).*$/", $url, $match);
        if (empty($match)) {
            return false;
        } else {
            return true;
        }
    }
}
// 验证是否shell注入
if (!function_exists('pcfPreventShell')) 
{
    function pcfPreventShell($data = '')
    {
        $data = true;
        if (is_string($data) && (preg_match('/^phar:\/\//i', $data) || stristr($data, 'phar://'))) {
            $data = false;
        } else if (is_numeric($data)) {
            $data = intval($data);
        }
        return $data;
    }
}
// 转换SQL关键字
if (!function_exists('strip_sql')) 
{
    function strip_sql($string) {
        $pattern_arr = array(
                "/\bunion\b/i",
                "/\bselect\b/i",
                "/\bupdate\b/i",
                "/\bdelete\b/i",
                "/\boutfile\b/i",
                "/\bchar\b/i",
                "/\bconcat\b/i",
                "/\btruncate\b/i",
                "/\bdrop\b/i",            
                "/\binsert\b/i", 
                "/\brevoke\b/i", 
                "/\bgrant\b/i",      
                "/\breplace\b/i", 
                "/\brename\b/i",
                "/\bdeclare\b/i",
                "/\bexec\b/i",         
                "/\bdelimiter\b/i",
                "/\bphar\b\:/i",
                "/\bphar\b/i",
                "/\@(\s*)\beval\b/i",
                "/\beval\b/i",
        );
        $replace_arr = array(
                'ｕｎｉｏｎ',
                'ｓｅｌｅｃｔ',
                'ｕｐｄａｔｅ',
                'ｄｅｌｅｔｅ',
                'ｏｕｔｆｉｌｅ',
                'ｃｈａｒ',
                'ｃｏｎｃａｔ',
                'ｔｒｕｎｃａｔｅ',
                'ｄｒｏｐ',            
                'ｉｎｓｅｒｔ',
                'ｒｅｖｏｋｅ',
                'ｇｒａｎｔ',
                'ｒｅｐｌａｃｅ',
                'ｒｅｎａｍｅ',
                'ｄｅｃｌａｒｅ',                
                'ｅｘｅｃ',         
                'ｄｅｌｉｍｉｔｅｒ',
                'ｐｈａｒ',
                'ｐｈａｒ',
                '＠ｅｖａｌ',
                'ｅｖａｌ',
        );
        return is_array($string) ? array_map('strip_sql', $string) : preg_replace($pattern_arr, $replace_arr, $string);
    }
}
// 获取拼音以gbk编码为准
if ( ! function_exists('get_pinyin'))
{
    function get_pinyin($str, $ishead = 0, $isclose = 1)
    {
        $s1 = iconv("UTF-8","gb2312", $str);
        $s2 = iconv("gb2312","UTF-8", $s1);
        if($s2 == $str){$str = $s1;}
        $pinyins = [];
        $restr = '';
        $str = trim($str);
        $slen = strlen($str);
        if($slen < 2)
        {
            return $str;
        }
        if(empty($pinyins))
        {
            $fp = fopen(WWW_ROOT.'extend/pinyin.dat', 'r');
            while(!feof($fp))
            {
                $line = trim(fgets($fp));
                $pinyins[$line[0].$line[1]] = substr($line, 3, strlen($line)-3);
            }
            fclose($fp);
        }
        for($i=0; $i<$slen; $i++)
        {
            if(ord($str[$i])>0x80)
            {
                $c = $str[$i].$str[$i+1];
                $i++;
                if(isset($pinyins[$c]))
                {
                    if($ishead==0)
                    {
                        $restr .= $pinyins[$c];
                    }
                    else
                    {
                        $restr .= $pinyins[$c][0];
                    }
                }else
                {
                    $restr .= "_";
                }
            }else if( preg_match("/[a-z0-9]/i", $str[$i]) )
            {
                $restr .= $str[$i];
            }
            else
            {
                $restr .= "_";
            }
        }
        if($isclose==0)
        {
            unset($pinyins);
        }
        return strtolower($restr);
    }
}
// 强制把数值转为整型
if (!function_exists('eyIntval')) 
{
    function eyIntval($data)
    {
        if (is_array($data)) {
            foreach ($data as $key => $val) {
                $data[$key] = intval($val);
            }
        } else if (is_string($data) && stristr($data, ',')) {
            $arr = explode(',', $data);
            foreach ($arr as $key => $val) {
                $arr[$key] = intval($val);
            }
            $data = implode(',', $arr);
        } else {
            $data = intval($data);
        }
        return $data;
    }
}
// 重新生成数据表缓存字段文件
if (!function_exists('schemaTable')) 
{
    function schemaTable($name)
    {
        $table = $name;
        $prefix = config('database.connections.mysql.prefix');
        if (!preg_match('/^'.$prefix.'/i', $name)) {
            $table = $prefix.$name;
        }
        //调用命令行的指令
        Console::call('optimize:schema', ['--table', $table]);
    }
}
// 时间格式化
if (!function_exists('pcftime')) 
{
    function pcftime($time = 0)
    {
        return date('Y-m-d H:i:s', $time);
    }
}
// 获取文件内容
if (!function_exists('pcfcms_getfile')) 
{
    function pcfcms_getfile($url){
        if (trim($url)==''){return false;}
        $opts = array('http'=>array('method'=>"GET",'timeout'=>3));
        $cnt = 0;
        while($cnt < 3 && ($res = @file_get_contents($url, false, stream_context_create($opts)))===FALSE) $cnt++;
        if ($res === false){
           return false;
        }else{
           return $res;
        }
    }
}
// 获取阅读权限 
if ( ! function_exists('get_arcrank_list'))
{
    function get_arcrank_list()
    {
        $result = Db::name('arcrank')->order('id asc')->column('*', 'rank');
        return $result;
    }
}
// 获取指定栏目的文档数
if (!function_exists('get_total_arc')) 
{
    function get_total_arc($typeid)
    {
        $admininfo = session::get('admin_info');
        if($admininfo['role_id'] < 0 || $admininfo['auth_role_info']['only_oneself'] != 1){
            $map = [];
            $total = 0;
            $current_channel = Db::name('arctype')->where('id', $typeid)->value('current_channel');
            $allow_release_channel = config('pcfcms.allow_release_channel');
            if (in_array($current_channel, $allow_release_channel)) {
                $Arctype = new app\common\model\Arctype;
                $result = $Arctype->getHasChildren($typeid);
                $typeidArr = get_arr_column($result, 'id');
                $map[]= ['typeid','IN',$typeidArr];
                $map[]= ['channel','=',$current_channel];
                $total = Db::name('archives')->field('id')->where($map)->count();
            } 
        }else{
            $map = [];
            $total = 0;
            $current_channel = Db::name('arctype')->where('id', $typeid)->value('current_channel');
            $allow_release_channel = config('pcfcms.allow_release_channel');
            if (in_array($current_channel, $allow_release_channel)) {
                $Arctype = new app\common\model\Arctype;
                $result = $Arctype->getHasChildren($typeid);
                $typeidArr = get_arr_column($result, 'id');
                $map[]= ['typeid','IN',$typeidArr];
                $map[]= ['channel','=',$current_channel];
                $map[]= ['admin_id','=',$admininfo['admin_id']];
                $total = Db::name('archives')->field('id')->where($map)->count();
            }     
        }
        return $total;
    }
}
/**
* 递归删除文件夹
* @param string $path 目录路径
* @param boolean $delDir 是否删除空目录
*/
if (!function_exists('delFile')) 
{
    function delFile($path, $delDir = true) {
        if(!is_dir($path)){
            return false;       
        }
        $handle = opendir($path);
        if ($handle) {
            while (false !== ($item = readdir($handle))) {
                if ($item != "." && $item != ".."){
                    is_dir("$path/$item") ? delFile("$path/$item",$delDir) : unlink("$path/$item");
                }
            }
            closedir($handle);
            if ($delDir) {
                return rmdir($path);
            }
        }else {
            if (file_exists($path)) {
                return @unlink($path);
            } else {
                return false;
            }
        }
    }
}
/**
 *  过滤换行回车符
 * @param     string  $str 字符串信息
 */
if (!function_exists('filter_line_return')) 
{
    function filter_line_return($str = '', $replace = '')
    {
        return str_replace(PHP_EOL, $replace, $str);
    }
}
/**
 * 获取随机字符串
 * @param int $randLength  长度
 * @param int $addtime  是否加入当前时间戳
 * @param int $includenumber   是否包含数字
 */
if (!function_exists('get_rand_str')) 
{ 
    function get_rand_str($randLength=6,$addtime=1,$includenumber=0){
        if (1 == $includenumber){
            $chars='ABCDEFGHJKLMNPQEST';
        } else if (2 == $includenumber) {
            $chars='123456789';
        } else {
            $chars='abcdefghijklmnopqrstuvwxyz';
        }
        $len=strlen($chars);
        $randStr='';
        for ($i=0;$i<$randLength;$i++){
            $randStr.=$chars[rand(0,$len-1)];
        }
        $tokenvalue=$randStr;
        if ($addtime){
            $tokenvalue=$randStr.time();
        }
        return $tokenvalue;
    }
}
/**
* 将数据库中查出的列表以指定的 id 作为数组的键名 
* @param array $arr 数组
* @param string $key_name 数组键名
*/
if (!function_exists('convert_arr_key')) 
{
    function convert_arr_key($arr, $key_name)
    {
        if (function_exists('array_column')) {
            return array_column($arr, null, $key_name);
        }
        $arr2 = [];
        foreach($arr as $key => $val){
            $arr2[$val[$key_name]] = $val;        
        }
        return $arr2;
    }
}
// 获取一级栏目的目录名称
if (!function_exists('every_top_dirname_list')) 
{
    function every_top_dirname_list() {
        $ArctypeModel = new ArctypeModel();
        $result = $ArctypeModel->getEveryTopDirnameList();
        return $result;
    }
}
/**
* 处理子目录与根目录的图片平缓切换
* @param string $str 图片路径或html代码
*/
if (!function_exists('handle_subdir_pic')) 
{
    function handle_subdir_pic($str = '', $type = 'img')
    {
        switch ($type) {
            case 'img':
                if (!is_http_url($str) && !empty($str)) {
                    $str = preg_replace('#^(/[/\w]+)?(public/uploads/|public/uploads/)#i',WWW_ROOT.'$2',$str);
                }else if (is_http_url($str) && !empty($str)) {
                    $str     = preg_replace('#^(/[/\w]+)?(public/uploads/|public/uploads/)#i',WWW_ROOT.'$2',$str);
                    $StrData = parse_url($str);
                    $strlen  = strlen(WWW_ROOT);
                }
                break;
            case 'html':
                $str = preg_replace('#(.*)(\#39;|&quot;|"|\')(/[/\w]+)?(public/uploads/|public/plugins/|public/uploads/)(.*)#iU','$1$2'.WWW_ROOT.'$4$5',$str);
                break;
            case 'soft':
                if (!is_http_url($str) && !empty($str)) {
                    $str = preg_replace('#^(/[/\w]+)?(public/uploads/soft/|public/uploads/soft/)#i','$2',$str);
                }
                break;
            default:
                break;
        }
        return $str;
    }
}
// 追加指定内嵌样式到编辑器内容的img标签，兼容图片自动适应页面
if (!function_exists('img_style_wh')) 
{
    function img_style_wh($content = '', $title = '')
    {
        if (!empty($content)) {
            preg_match_all('/<img.*(\/)?>/iUs', $content, $imginfo);
            $imginfo = !empty($imginfo[0]) ? $imginfo[0] : [];
            if (!empty($imginfo)) {
                $num = 1;
                $appendStyle = "max-width:100%!important;height:auto;";
                $title = preg_replace('/("|\')/i', '', $title);
                foreach ($imginfo as $key => $imgstr) {
                    $imgstrNew = $imgstr;
                    // 兼容已存在的多重追加样式，处理去重
                    if (stristr($imgstrNew, $appendStyle.$appendStyle)) {
                        $imgstrNew = preg_replace('/'.$appendStyle.$appendStyle.'/i', '', $imgstrNew);
                    }
                    if (stristr($imgstrNew, $appendStyle)) {
                        $content = str_ireplace($imgstr, $imgstrNew, $content);
                        $num++;
                        continue;
                    }
                    // 追加style属性
                    $imgstrNew = preg_replace('/style(\s*)=(\s*)[\'|\"](.*?)[\'|\"]/i', 'style="'.$appendStyle.'${3}"', $imgstrNew);
                    if (!preg_match('/<img(.*?)style(\s*)=(\s*)[\'|\"](.*?)[\'|\"](.*?)[\/]?(\s*)>/i', $imgstrNew)) {
                        // 新增style属性
                        $imgstrNew = str_ireplace('<img', "<img style=\"".$appendStyle."\" ", $imgstrNew);
                    }
                    // 追加alt属性
                    $altNew = $title."(图{$num})";
                    $imgstrNew = preg_replace('/alt(\s*)=(\s*)[\'|\"]([\w\.]*?)[\'|\"]/i', 'alt="'.$altNew.'"', $imgstrNew);
                    if (!preg_match('/<img(.*?)alt(\s*)=(\s*)[\'|\"](.*?)[\'|\"](.*?)[\/]?(\s*)>/i', $imgstrNew)) {
                        // 新增alt属性
                        $imgstrNew = str_ireplace('<img', "<img alt=\"{$altNew}\" ", $imgstrNew);
                    }
                    // 追加title属性
                    $titleNew = $title."(图{$num})";
                    $imgstrNew = preg_replace('/title(\s*)=(\s*)[\'|\"]([\w\.]*?)[\'|\"]/i', 'title="'.$titleNew.'"', $imgstrNew);
                    if (!preg_match('/<img(.*?)title(\s*)=(\s*)[\'|\"](.*?)[\'|\"](.*?)[\/]?(\s*)>/i', $imgstrNew)) {
                        // 新增alt属性
                        $imgstrNew = str_ireplace('<img', "<img alt=\"{$titleNew}\" ", $imgstrNew);
                    }
                    // 新的img替换旧的img
                    $content = str_ireplace($imgstr, $imgstrNew, $content);
                    $num++;
                }
            }
        }
        return $content;
    }
}
/**
* 字符串截取，支持中文和其他编码
* @param string $str 需要转换的字符串
* @param string $start 开始位置
* @param string $length 截取长度
* @param string $suffix 截断显示字符
* @param string $charset 编码格式
*/
if (!function_exists('pcf_msubstr')) 
{
    function pcf_msubstr($str="", $start=0, $length="", $suffix=false, $charset="utf-8") {
        if(function_exists("mb_substr"))
            $slice = mb_substr($str, $start, $length, $charset);
        elseif(function_exists('iconv_substr')) {
            $slice = iconv_substr($str,$start,$length,$charset);
            if(false === $slice) {$slice = "";}
        }else{
            $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("",array_slice($match[0], $start, $length));
        }
        $str_len = strlen($str); // 原字符串长度
        $slice_len = strlen($slice); // 截取字符串的长度
        if ($slice_len < $str_len) {
            $slice = $suffix ? $slice.'...' : $slice;
        }
        return $slice;
    }
}
/**
 * 消费日志
 * $log_info 记录信息
 * $type 类型 1: 充值记录 ，2: 消费记录，3：下载记录，4：更新记录
 */
if (!function_exists('order_Log')) 
{
    function order_Log($log_info, $type = 1)
    {
       if(isset($log_info['user_id']) && session::get('pcfcms_users_id') > 0 && $log_info['user_id'] > 0){
            if($type == 1){
                $add['user_id'] = isset($log_info['user_id']) ? $log_info['user_id'] : 0;
                $add['aid'] = isset($log_info['aid']) ? $log_info['aid'] : 0;
                $add['order_title'] = isset($log_info['order_title']) ? $log_info['order_title'] :"";
                if(isset($log_info['order_sn']) && !empty($log_info['order_sn'])){
                   $add['order_sn'] = $log_info['order_sn'];
                }else{
                   $add['order_sn'] = ""; 
                }
                $add['order_type'] = 1;
                $add['order_num'] = 1;
                $add['order_price'] = isset($log_info['price']) ? $log_info['price'] : 0;
                $add['add_time'] = time();
                return Db::name('order_log')->save($add);
            }elseif ($type == 2) {
                $add['user_id'] = $log_info['user_id'];
                $add['aid'] = isset($log_info['aid']) ? $log_info['aid'] :0;
                $add['order_title'] = $log_info['order_title'];
                if(isset($log_info['order_sn'])){
                   $add['order_sn'] = $log_info['order_sn'];
                }
                $add['order_type'] = 2;
                $add['order_num'] = $log_info['order_num'];
                $add['order_price'] = $log_info['price'];
                $add['add_time'] = time();
                return Db::name('order_log')->save($add);
            }elseif ($type == 3) {
                $add['aid'] = isset($log_info['aid']) ? $log_info['aid'] :0;
                $add['user_id'] = $log_info['user_id'];
                $add['order_title'] = $log_info['order_title'];
                if(isset($log_info['order_sn'])){
                   $add['order_sn'] = $log_info['order_sn'];
                }
                $add['order_type'] = 3;
                $add['order_num'] = $log_info['order_num'];
                $add['order_price'] = $log_info['price'];
                $add['add_time'] = time();
                return Db::name('order_log')->save($add);
            }elseif ($type == 4) {
                $add['aid'] = isset($log_info['aid']) ? $log_info['aid'] :0;
                $add['user_id'] = $log_info['user_id'];
                $add['order_title'] = $log_info['order_title'];
                if(isset($log_info['order_sn'])){
                   $add['order_sn'] = $log_info['order_sn'];
                }
                $add['order_type'] = 3;
                $add['order_num'] = $log_info['order_num'];
                $add['order_price'] = $log_info['price'];
                $add['add_time'] = time();
                return Db::name('order_log')->where('id', $log_info['id'])->update($add);
            }        
       }
    }
}
/////////////////////////////////////系统自定义函数区域////////////////////////


//////////////////////////////////////缓存函数区域//////////////////////////////
/**
 * 获取缓存或者更新缓存，只适用于config表
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据['k1'=>'v1','k2'=>'v3']
 * @param array $options 缓存配置
 */
if (!function_exists('sysConfig')) 
{
    function sysConfig($config_key,$data = []){
        $tableName = 'config';
        $table_db = Db::name($tableName);
        $param = explode('.', $config_key);
        $cache_inc_type = $tableName.$param[0];
        $newData = [];
        if(empty($data)){
            $config = Cache::get($cache_inc_type);//直接获取缓存文件
            if(empty($config)){
                //缓存文件不存在就读取数据库
                if ($param[0] == 'global') {
                    $param[0] = 'global';
                    $res = $table_db->select()->toArray();
                } else {
                    $res = $table_db->where(['inc_type'=> $param[0]])->select()->toArray();
                }
                $config  = [];
                if($res){
                    foreach($res as $k=>$val){
                        if(isset($val) && is_array($val)){
                           $config[$val['name']] = $val['value']; 
                        }
                    }
                    Cache::tag('global_config')->set($cache_inc_type, $config, ADMIN_CACHE_TIME);
                }
            }
            if(!empty($param) && count($param)>1){
                $newKey = strtolower($param[1]);
                return isset($config[$newKey]) ? $config[$newKey] : '';
            }else{
                return $config;
            }
        }else{
            //更新缓存
            $result =  $table_db->where(['inc_type'=> $param[0]])->select()->toArray();
            if($result){
                foreach($result as $val){
                    $temp[$val['name']] = $val['value'];
                }
                $add_data = [];
                foreach ($data as $k=>$v){
                    $newK = strtolower($k);
                    $newArr = [
                        'name'=>$newK,
                        'value'=>$v,
                        'inc_type'=>$param[0],
                        'update_time'=> time()
                    ];
                    if(!isset($temp[$newK])){
                        array_push($add_data, $newArr); //新key数据插入数据库
                    }else{
                        if ($v != $temp[$newK]) {
                            Db::name('config')->where('name',$newK)->update($newArr);//缓存key存在且值有变更新此项
                        }
                    }
                }
                if (!empty($add_data)) {
                    $table_db->insertAll($add_data);
                }
                //更新后的数据库记录
                $newRes = $table_db->where(['inc_type'=> $param[0]])->select()->toArray();
                foreach ($newRes as $rs){
                    $newData[$rs['name']] = $rs['value'];
                }
            }else{
                if ($param[0] != 'global') {
                    foreach($data as $k=>$v){
                        $newK = strtolower($k);
                        $newArr[] = [
                            'name'=>$newK,
                            'value'=>trim($v),
                            'inc_type'=>$param[0],
                            'update_time' => time(),
                        ];
                    }
                    if(!empty($newArr)){
                        $table_db->insertAll($newArr);
                    }
                }
                $newData = $data;
            }
            $result = false;
            $res = $table_db->select()->toArray();
            if($res){
                $global = [];
                foreach($res as $k=>$val){
                    $global[$val['name']] = $val['value'];
                }
                $result = Cache::tag('global_config')->set($tableName.'global', $global, ADMIN_CACHE_TIME);
            }
            if ($param[0] != 'global') {
                $result = Cache::tag('global_config')->set($cache_inc_type, $newData, ADMIN_CACHE_TIME);
            }
            return $result;
        }
    }
}
//获取查询排序，用于标签文件 TagArclist / TagList
if (!function_exists('getOrderBy'))
{
    function getOrderBy($orderby,$orderWay,$isrand = false){
        switch ($orderby) {
            case 'hot':
            case 'click':
                $orderby = "a.click {$orderWay}";
                break;
            case 'id':
            case 'aid':
                $orderby = "a.aid {$orderWay}";
                break;
            case 'now':
            case 'new':
            case 'add_time':
                $orderby = "a.add_time {$orderWay}";
                break;
            case 'sort_order':
                $orderby = "a.sort_order {$orderWay}";
                break;
            case 'rand':
                if (true === $isrand) {
                    $orderby = "rand()";
                } else {
                    $orderby = "a.aid {$orderWay}";
                }
                break;
            default:
            {
                if (empty($orderby)) {
                    $orderby = 'a.sort_order asc, a.aid desc';
                } elseif (trim($orderby) != 'rand()') {
                    $orderbyArr = explode(',', $orderby);
                    foreach ($orderbyArr as $key => $val) {
                        $val = trim($val);
                        if (preg_match('/^([a-z]+)\./i', $val) == 0) {
                            $val = 'a.'.$val;
                            $orderbyArr[$key] = $val;
                        }
                    }
                    $orderby = implode(',', $orderbyArr);
                }
                break;
            }
        }
        return $orderby;
    }
}
//////////////////////////////////////缓存函数区域//////////////////////////////


///////////////////////////////权限验证和菜单区域//////////////////////////////
//权限验证
if (!function_exists('appfile_popedom')) 
{
    function appfile_popedom($string)
    {
       $where = [];
       $where[] = ['auth','<>',''];
       $where[] = ['parent_id','<>',0];
       $pauth = Db::name('menu')->field('auth')->where($where)->select()->toArray();
       foreach ($pauth as $k => $v) {
           $ordernum[] = $v['auth'];
       }
       $ordernum = array_unique($ordernum); 
       foreach ($ordernum as $key => $value) {
            $ordernum1[$value] = true;
       }
       $admin_popedom = Session::get('admin_info.auth_role_info.permission');
       $role_id =  Session::get('admin_info.role_id');
       if($role_id < 0){
           return $ordernum1;
       }else{
            if(!$string) return false;
            if($string == 'content/index'){
               $p_rs = Db::name('menu')->where('param',$string)->find();
            }else{
               $p_rs = Db::name('menu')->where('url',$string)->find();
            }
            if(!$p_rs) return false;
            $gid = $p_rs["id"];
            if(Session::get('role_id') < 0){
                return $ordernum1;
            }else{
                $rslist = Db::name('menu')->where('parent_id',$gid)->select()->toArray();
            }
            if(!$rslist) return false;
            $list = [];
            foreach($rslist AS $key=>$value){
                if($admin_popedom && in_array($value["id"],$admin_popedom)){
                    $list[$value["auth"]] = true;
                }else{
                    $list[$value["auth"]] = false;
                }
            }
            return $list;    
        }
    }
}
//后台左侧菜单
if (!function_exists('getMenuList'))
{
    function getMenuList() {
        $menuArr = Cache::get('getMenuList');
        if(!$menuArr){
            $menuArr = Db::name('menu')->where(['parent_id'=>0,'is_show'=>1,'status'=>1])->column('*', 'id');
            foreach ($menuArr as $key => $value) {
                if($value['id'] == 2){
                   //内容管理
                   $menuArr[$key]['child'] = getmenucontent();
                }else{
                   $menuArr[$key]['child'] = getchandList($value['id']); 
                }
                if(!empty($value['url'])){
                   $menuArr[$key]['url'] = '/'.$value['url']; 
                }
            }
            Cache::tag('getmenu_cache')->set('getMenuList', $menuArr, ADMIN_CACHE_TIME);
        }
        return $menuArr;
    }
}
//获取模块导航
if (!function_exists('getchandList'))
{
    function getchandList($id) {
        $getchild1list = Db::name('menu')
                       ->where(['parent_id'=>$id,'is_show'=>1,'status'=>1])
                       ->where('type','<>',4)
                       ->order('sort asc')
                       ->column('*', 'id');
        foreach ($getchild1list as $key => $value) {
            $getchild1list[$key]['child'] = noallgetlist($value['id']);
            if(!empty($value['url'])){
               $getchild1list[$key]['url'] = '/'.$value['url']; 
            }
        } 
        foreach ($getchild1list as $k => $val) {
            if(empty($val['url']) && empty($val['child'])){
                unset($getchild1list[$key]);
            }
        }
        return $getchild1list;
    }
}
//过滤左侧导航没权限的导航
if (!function_exists('noallgetlist'))
{
    function noallgetlist($id) {
        $getchild1list = Db::name('menu')
        ->where(['parent_id'=>$id,'is_show'=>1,'status'=>1])
        ->where('type','<>',4)
        ->order('sort asc')
        ->column('*', 'id');
        $admin_popedom = Session::get('admin_info.auth_role_info.permission');
        foreach ($getchild1list as $key => $value) {
            if(!empty($value['url'])){
               $getchild1list[$key]['url'] = '/'.$value['url']; 
            }
            $getchild = Db::name('menu')
            ->where(['parent_id'=>$value['id'],'is_show'=>1,'status'=>1,'auth'=>'list'])
            ->where('type','<>',4)
            ->order('sort asc')
            ->column('*', 'id');
            if(Session::get('admin_info.role_id') > 0){
                foreach ($getchild as $k => $val) {
                    if($admin_popedom && !in_array($val["id"],$admin_popedom)){
                        unset($getchild1list[$key]);
                    }
                    if(!empty($val['url'])){
                       $getchild[$k]['url'] = '/'.$val['url']; 
                    }
                }                
            }
        }
        return $getchild1list;
    }
}
//获取内容管理列表
if (!function_exists('getmenucontent'))
{
    function getmenucontent() {
        $channel_type = Db::name('channel_type')->where('status',1)->order('sort_order asc')->column('*', 'id');
        $newchannel_type = [];
        foreach ($channel_type as $k => $val) {
           $newchannel_type[$k]['id'] = $val['id'];
           $newchannel_type[$k]['parent_id'] = 2;
           $newchannel_type[$k]['name'] = $val['ntitle']."管理";
           $newchannel_type[$k]['icon'] = $val['icon'];
           $newchannel_type[$k]['url'] = '';
           $newchannel_type[$k]['param'] = '';
           $newchannel_type[$k]['type'] = 2;
           $newchannel_type[$k]['auth'] = '';
           $newchannel_type[$k]['sort'] = '';
           $newchannel_type[$k]['create_time'] = $val['add_time'];
           $newchannel_type[$k]['update_time'] = $val['update_time'];
           $newchannel_type[$k]['lang'] = $val['lang'];
           $newchannel_type[$k]['is_show'] = 1;
           $newchannel_type[$k]['status'] = 1;
           if($val['ifsystem'] == 1 && $val['id'] == 6){
               $newchannel_type[$k]['child'] = [
                    '11'=>array(
                        'id'=>11,
                        'parent_id'=>$val['id'],
                        'name'=> $val['ntitle']."管理",
                        'icon'=>'',
                        'url'=> pcfurl("/arctype/index",['current_channel'=> $val['id'],'lang'=> $val['lang']],false,false),
                        'param'=>'',
                        'type'=>3,
                        'auth'=>'',
                        'sort'=>'',
                        'create_time'=>$val['add_time'],
                        'update_time'=>$val['update_time'],
                        'lang'=>$val['lang'],
                        'is_show'=>1,
                        'status'=>1
                    ),
               ];
           }else if($val['ifsystem'] == 1 && $val['id'] != 6){
               $newchannel_type[$k]['child'] = [
                   /*'11'=>array(
                        'id'=>11,
                        'parent_id'=>$val['id'],
                        'name'=>"添加".$val['ntitle'],
                        'icon'=>'',
                        'url'=> pcfurl("/".$val['nid']."/add",['current_channel'=> $val['id'],'lang'=> $val['lang']],false,false),
                        'param'=>'',
                        'type'=>3,
                        'auth'=>'',
                        'sort'=>'',
                        'create_time'=>$val['add_time'],
                        'update_time'=>$val['update_time'],
                        'lang'=>$val['lang'],
                        'is_show'=>1,
                        'status'=>1
                    ),*/
                    '22'=>array(
                        'id'=>22,
                        'parent_id'=>$val['id'],
                        'name'=> $val['ntitle']."管理",
                        'icon'=>'',
                        'url'=> pcfurl("/".$val['nid']."/index",['current_channel'=> $val['id'],'lang'=> $val['lang']],false,false),
                        'param'=>'',
                        'type'=>3,
                        'auth'=>'',
                        'sort'=>'',
                        'create_time'=>$val['add_time'],
                        'update_time'=>$val['update_time'],
                        'lang'=>$val['lang'],
                        'is_show'=>1,
                        'status'=>1
                    ),
                    '33'=>array(
                        'id'=>33,
                        'parent_id'=>$val['id'],
                        'name'=> $val['ntitle']."分类",
                        'icon'=>'',
                        'url'=> pcfurl("/arctype/index",['current_channel'=> $val['id'],'lang'=> $val['lang']],false,false),
                        'param'=>'',
                        'type'=>3,
                        'auth'=>'',
                        'sort'=>'',
                        'create_time'=>$val['add_time'],
                        'update_time'=>$val['update_time'],
                        'lang'=>$val['lang'],
                        'is_show'=>1,
                        'status'=>1
                    ),
               ];
           }else{
               $newchannel_type[$k]['child'] = [
                   /*'11'=>array(
                        'id'=>11,
                        'parent_id'=>$val['id'],
                        'name'=>"添加".$val['ntitle'],
                        'icon'=>'',
                        'url'=> pcfurl("/custom/add",['current_channel'=> $val['id'],'lang'=> $val['lang']],false,false),
                        'param'=>'',
                        'type'=>3,
                        'auth'=>'',
                        'sort'=>'',
                        'create_time'=>$val['add_time'],
                        'update_time'=>$val['update_time'],
                        'lang'=>$val['lang'],
                        'is_show'=>1,
                        'status'=>1
                    ),*/
                    '22'=>array(
                        'id'=>22,
                        'parent_id'=>$val['id'],
                        'name'=> $val['ntitle']."管理",
                        'icon'=>'',
                        'url'=> pcfurl("/custom/index",['current_channel'=> $val['id'],'lang'=> $val['lang']],false,false), 
                        'param'=>'',
                        'type'=>3,
                        'auth'=>'',
                        'sort'=>'',
                        'create_time'=>$val['add_time'],
                        'update_time'=>$val['update_time'],
                        'lang'=>$val['lang'],
                        'is_show'=>1,
                        'status'=>1
                    ),
                    '33'=>array(
                        'id'=>33,
                        'parent_id'=>$val['id'],
                        'name'=> $val['ntitle']."分类",
                        'icon'=>'',
                        'url'=> pcfurl("/arctype/index",['current_channel'=> $val['id'],'lang'=> $val['lang']],false,false),
                        'param'=>'',
                        'type'=>3,
                        'auth'=>'',
                        'sort'=>'',
                        'create_time'=>$val['add_time'],
                        'update_time'=>$val['update_time'],
                        'lang'=>$val['lang'],
                        'is_show'=>1,
                        'status'=>1
                    ),
               ];
           }
        }
        return $newchannel_type;
    }
}
//角色权限获取栏目
if (!function_exists('getchandList1'))
{
    function getchandList1($id) {
        $getchild1list = Db::name('menu')->where(['parent_id'=>$id,'is_show'=>1])->order('sort asc')->column('*', 'id');
        foreach ($getchild1list as $key => $value) {
            $getchild1list[$key]['child'] = getchandList2($value['id']);
        }
        return $getchild1list;
    }
}
//角色权限获取子栏目节点
if (!function_exists('getchandList2'))
{
    function getchandList2($id) {
        $getchild2list = Db::name('menu')->where(['parent_id'=>$id,'is_show'=>1])->order('sort asc')->column('*', 'id');
        foreach ($getchild2list as $key => $value) {
            $getchild2list[$key]['child'] = Db::name('menu')
            ->where(['parent_id'=>$value['id'],'is_show'=>1])
            ->column('*', 'id');
        }
        return $getchild2list;
    }
}
///////////////////////////////权限验证和菜单区域//////////////////////////////


///////////////////////////////URL生成开始//////////////////////////////////////
// URL模式下拉列表
if (!function_exists('get_seo_pseudo_list')) 
{
    function get_seo_pseudo_list($key= '')
    {
        $data = array(
            1   => '动态URL',
            2   => '伪静态化'
        );
        return isset($data[$key]) ? $data[$key] : $data;
    }
}
/**
 * 获取栏目链接
 * @param array $arctype_info 栏目信息
 * @param $admin 后台访问链接，还是前台链接
 * @param URL模式  1:动态，2：伪静态
 */
if (!function_exists('get_typeurl')) 
{
    function get_typeurl($arctype_info = [], $admin = true)
    {
        $domain = request::domain();
        // 兼容采集没有归属栏目的文档
        if (empty($arctype_info['current_channel'])) {
            $channelRow = Db::name('channel_type')->field('id as channel')->where('id',1)->find();
            $arctype_info = array_merge($arctype_info, $channelRow);
        }
        static $result = null;
        null === $result && $result = Db::name('channel_type')->column('id, ctl_name', 'id');
        static $ctl_name = null;
        if ($result) {
            $ctl_name = $result[$arctype_info['current_channel']]['ctl_name'];
        }
        static $seo_pseudo = null;
        static $seo_rewrite_format = null;
        if (null === $seo_pseudo || null === $seo_rewrite_format) {
            $seoConfig = sysConfig('seo');
            $seo_pseudo = !empty($seoConfig['seo_pseudo']) ? $seoConfig['seo_pseudo'] : config('pcfcms.admin_config.seo_pseudo');
            $seo_rewrite_format = !empty($seoConfig['seo_rewrite_format']) ? $seoConfig['seo_rewrite_format'] : config('pcfcms.admin_config.seo_rewrite_format');
        }
        // 默认后台打开
        if ($admin) {
            $typeurl = pcfurl('Lists/index', ['tid' =>$arctype_info['id']], true, $domain);
        } else {
            $typeurl = typeurl("{$ctl_name}/lists", $arctype_info, true, $domain, $seo_pseudo, $seo_rewrite_format);
        }
        return $typeurl;
    }
}
/**
 * 栏目Url生成
 * @param string        $url 路由地址
 * @param string|array  $param 变量
 * @param bool|string   $suffix 生成的URL后缀
 * @param bool|string   $domain 域名
 * @param string        $seo_pseudo URL模式  1:动态，2：伪静态
 * @param string        $seo_pseudo_format URL格式
 */
if (!function_exists('typeurl')) 
{
    function typeurl($url = '', $param = '', $suffix = true, $domain = false, $seo_pseudo = null, $seo_pseudo_format = null)
    {
        static $gzpcfUrl = null;
        $seo_inlet = config('pcfcms.admin_config.seo_inlet');       
        $seo_pseudo = !empty($seo_pseudo) ? $seo_pseudo : sysConfig('seo.seo_pseudo');
        $seo_pseudo_format = !empty($seo_pseudo_format) ? $seo_pseudo_format : sysConfig('seo.seo_rewrite_format');
        if ($seo_pseudo == 1) {
            // 动态
            if (is_array($param)) {
                $vars = ['tid' => $param['id']];
                $vars = http_build_query($vars);
            } else {
                $vars = $param;
            }
            $gzpcfUrl = pcfurl('/Lists/index', [], $suffix, $domain);
            $urlParam = parse_url($gzpcfUrl);
            $query_str = isset($urlParam['query']) ? $urlParam['query'] : '';
            if (empty($query_str)) {
                $gzpcfUrl .= '?';
            } else {
                $gzpcfUrl .= '&';
            }
            $gzpcfUrl .= $vars;
        }elseif ($seo_pseudo == 2) {
            if (1 == intval($seo_pseudo_format)) {
                $url = 'Lists/index';
            }
            //伪静态
            if (is_array($param)) {
                $vars = array(
                    'tid' => $param['dirname']
                );
            } else {
                $vars = $param;
            }
            $gzpcfUrl = pcfurl($url, $vars, $suffix, $domain);
        }
        return $gzpcfUrl;
    }
}
/**
 * 获取文档链接
 * @param array $arctype_info 栏目信息
 * @param boolean $admin 后台访问链接，还是前台链接
 */
if (!function_exists('get_arcurl')) 
{
    function get_arcurl($arcview_info = [], $admin = true)
    {
        $domain = request::domain();
        $admin_id = session::get('admin_id');
        $seo_inlet = config('pcfcms.admin_config.seo_inlet');// 是否隐藏index.php   
        // 兼容采集没有归属栏目的文档
        if (empty($arcview_info['channel'])) {
            $channelRow = Db::name('channel_type')->field('id as channel')->where('id',1)->find();
            $arcview_info = array_merge($arcview_info, $channelRow);
        }
        static $result = null;
        null === $result && $result = Db::name('channel_type')->column('id, ctl_name', 'id');
        static $ctl_name = null;
        if ($result) {
            $ctl_name = $result[$arcview_info['channel']]['ctl_name'];
        }
        static $seo_pseudo = null;
        static $seo_rewrite_format = null;
        if (null === $seo_pseudo || null === $seo_rewrite_format) {
            $seoConfig = sysConfig('seo');
            $seo_pseudo = !empty($seoConfig['seo_pseudo']) ? $seoConfig['seo_pseudo'] : config('pcfcms.admin_config.seo_pseudo');
            $seo_rewrite_format = !empty($seoConfig['seo_rewrite_format']) ? $seoConfig['seo_rewrite_format'] : config('pcfcms.admin_config.seo_rewrite_format');
        }
        if ($admin) {
            $arcurl = arcurl("{$ctl_name}/view", $arcview_info, true, $domain, $seo_pseudo, $seo_rewrite_format);
            if(1==$seo_rewrite_format){
               $arcurl = str_replace('/View', '', $arcurl);
            }
        } else {
            $arcurl = arcurl("{$ctl_name}/view", $arcview_info, true, $domain, $seo_pseudo, $seo_rewrite_format);
        }
        return $arcurl;
    }
}
/**
 * 文档Url生成
 * @param string        $url 路由地址
 * @param string|array  $param 变量
 * @param bool|string   $suffix 生成的URL后缀
 * @param bool|string   $domain 域名
 * @param string        $seo_pseudo URL模式  1:动态，2：伪静态
 * @param string        $seo_pseudo_format URL格式
 */
if (!function_exists('arcurl')) 
{
    function arcurl($url = '', $param = '', $suffix = true, $domain = false, $seo_pseudo = '', $seo_pseudo_format = null)
    {
        static $gzpcfUrl = null;        
        $seo_pseudo = !empty($seo_pseudo) ? $seo_pseudo : sysConfig('seo.seo_pseudo');
        static $seo_rewrite_format = null;
        null === $seo_rewrite_format && $seo_rewrite_format = config('pcfcms.admin_config.seo_rewrite_format');
        if ($seo_pseudo == 1) {
            // 动态 
            if (is_array($param)) {
                $vars = array('aid' => $param['aid']);
                $vars = http_build_query($vars);
            } else {
                $vars = $param;
            }
            $gzpcfUrl = pcfurl('/View/index', [], $suffix, $domain);
            $urlParam = parse_url($gzpcfUrl);
            $query_str = isset($urlParam['query']) ? $urlParam['query'] : '';
            if (empty($query_str)) {
                $gzpcfUrl .= '?';
            } else {
                $gzpcfUrl .= '&';
            }
            $gzpcfUrl .= $vars;
        }elseif ($seo_pseudo == 2) {
            if (1 == intval($seo_rewrite_format)) {
                $url = 'View/index';
                /*static $tdirnameArr = null; // URL里第一层级固定是顶级栏目的目录名称
                null === $tdirnameArr && $tdirnameArr = every_top_dirname_list();
                if (!empty($param['dirname']) && isset($tdirnameArr[md5($param['dirname'])]['tdirname'])) {
                    $param['dirname'] = $tdirnameArr[md5($param['dirname'])]['tdirname'];
                }*/
            }
            if (is_array($param)) {
                $vars = array(
                    'aid' => $param['aid'],
                    'dirname' => $param['dirname']
                );
            } else {
                $vars = $param;
            }
            $gzpcfUrl = pcfurl($url, $vars, $suffix, $domain);
        }
        return $gzpcfUrl;
    }
}
/**
 * pcfurl生成
 * @param string        $url 路由地址
 * @param string|array  $vars 变量
 * @param bool|string   $suffix 生成的URL后缀
 * @param bool|string   $domain 域名
 * @param bool|string   $admin 后台加上入口文件
 */
if (!function_exists('pcfurl')) 
{
    function pcfurl($url = '',$vars = '',$suffix = true,$domain = false,$admin = false)
    { 
        $newurl = "";   
        $seo_pseudo = !empty($seo_pseudo) ? $seo_pseudo : sysConfig('seo.seo_pseudo');
        $seo_inlet = sysConfig('seo.seo_inlet');
        if (1 == $seo_inlet) {
            if($suffix){
              $url = url($url, $vars)->suffix(true)->root(false)->build();
            }else{
              $url = url($url, $vars)->suffix(false)->root(false)->build();  
            }
        }else{
            if($suffix){
              $url = url($url, $vars)->suffix(true)->root('/index.php')->build();
            }else{
              $url = url($url, $vars)->suffix(false)->root('/index.php')->build();  
            }
        }
        if($seo_pseudo == 1){$url = strtolower($url);} // 强制转小写
        $newurl = str_replace('/home', '', $url);//访问前台 
        $newurl = str_replace('/admin', '', $newurl);//后台访问前台
        $newa = substr($newurl,0,strrpos($newurl,'php'));
        $newa = $newa."php";
        $newurl = str_replace($newa, '', $newurl);//后台访问前台
        if($admin){
           $newurl = sysConfig('web.web_adminbasefile').$newurl;
        }else{
           $newurl = $newurl;  
        }
        if($domain){
           $newurl = request()->domain().$newurl;
        }else{
           $newurl = $newurl;  
        }
        return $newurl;
    }
}
///////////////////////////////URL生成结束////////////////////////////////////











































































//域名过滤
if (!function_exists('cleanDomain')) 
{
    function cleanDomain($q,$w=0){ 
         $q = htmlspecialchars(strtolower(trim($q)));//整理域名 $w=1过滤www.前缀 $w=0不过滤
         if(substr($q,0,7) == "http://" || substr($q,0,8) == "https://" || substr($q,0,6) == "ftp://"){
              $q = str_replace("http:/","",$q);
              $q = str_replace("https:/","",$q);
              $q = str_replace("ftp:/","",$q);
         }
         if(substr($q,0,4) == "www." && $w==1) {
            $q = str_replace("www.","",$q);
         }
         $q = trim($q,"/");
         return $q;
    }
}
//城市定位
if (!function_exists('getCity')) 
{
    function getCity() 
    { 
        // 获取当前位置所在城市 
        $getIp = clientIP();
        $content = file_get_contents("http://api.map.baidu.com/location/ip?ak=wcPR9wtbvWO5dylkTbpxNXz5l7FydCdd&ip={$getIp}&coor=bd09ll");
        $json = json_decode($content, true); 
        if($json['status'] == 1){
            $address = "";
        }else{
            $address = $json['content']['address']; 
        } 
        return $address; 
    }
}
// 百度推送
if (!function_exists('BaiduPush')) 
{
    // $urls 推送地址；为一个数组。
    function BaiduPush($urls) 
    {
        $youdomain = \think\facade\request::domain(); //获取当前域名
        $youdomain = cleanDomain($youdomain,0);
        $urls = array($urls);
        $baidutoken = sysConfig('sitemap.sitemap_zzbaidutoken');
        $api = 'http://data.zz.baidu.com/urls?site='.$youdomain.'&token='.$baidutoken;
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        return $result;
    }
}
if (!function_exists('pcfcmssend_email')) 
{
    /**
     * 邮件发送
     * @param $to    接收人
     * @param string $subject   邮件标题
     * @param string $content   邮件内容(html模板渲染后的内容)
     */
    function pcfcmssend_email($to='', $subject='', $content= [],  $smtp_config = []){
        // 实例化类库，调用发送邮件
        $emailLogic = new \app\common\logic\EmailLogic();
        $res = $emailLogic->send_email($to, $subject, $content,$smtp_config);
        return $res;
    }
}


//客户端IP
if (!function_exists('clientIP')) 
{
    
    function clientIP() {
        $ip = request()->ip();
        if(preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d))))$/', $ip))          
            return $ip;
        else
            return '';
    }
}
if (!function_exists('checkStrHtml')) 
{
    /**
     * 过滤Html标签
     * @param     string  $string  内容
     * @return    string
     */
    function checkStrHtml($string){
        $string = pcftrim_space($string);
        if(is_numeric($string)) return $string;
        if(!isset($string) or empty($string)) return '';
        $string = preg_replace('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/','',$string);
        $string  = ($string);
        $string = strip_tags($string,""); //清除HTML如<br />等代码
        $string = str_replace("\n", "", $string);//去掉空格和换行
        $string = str_replace("\t","",$string); //去掉制表符号
        $string = str_replace(PHP_EOL,"",$string); //去掉回车换行符号
        $string = str_replace("\r","",$string); //去掉回车
        $string = str_replace("'","‘",$string); //替换单引号
        $string = str_replace("&amp;","&",$string);
        $string = str_replace("=★","",$string);
        $string = str_replace("★=","",$string);
        $string = str_replace("★","",$string);
        $string = str_replace("☆","",$string);
        $string = str_replace("√","",$string);
        $string = str_replace("±","",$string);
        $string = str_replace("‖","",$string);
        $string = str_replace("×","",$string);
        $string = str_replace("∏","",$string);
        $string = str_replace("∷","",$string);
        $string = str_replace("⊥","",$string);
        $string = str_replace("∠","",$string);
        $string = str_replace("⊙","",$string);
        $string = str_replace("≈","",$string);
        $string = str_replace("≤","",$string);
        $string = str_replace("≥","",$string);
        $string = str_replace("∞","",$string);
        $string = str_replace("∵","",$string);
        $string = str_replace("♂","",$string);
        $string = str_replace("♀","",$string);
        $string = str_replace("°","",$string);
        $string = str_replace("¤","",$string);
        $string = str_replace("◎","",$string);
        $string = str_replace("◇","",$string);
        $string = str_replace("◆","",$string);
        $string = str_replace("→","",$string);
        $string = str_replace("←","",$string);
        $string = str_replace("↑","",$string);
        $string = str_replace("↓","",$string);
        $string = str_replace("▲","",$string);
        $string = str_replace("▼","",$string);
        // --过滤微信表情
        $string = preg_replace_callback('/[\xf0-\xf7].{3}/', function($r) { return '';}, $string);
        return $string;
    }
}
if (!function_exists('pcftrim_space')) 
{
    /**
     * 过滤前后空格等多种字符
     *
     * @param string $str 字符串
     * @param array $arr 特殊字符的数组集合
     * @return string
     */
    function pcftrim_space($str, $arr = [])
    {
        if (empty($arr)) {
            $arr = array(' ', '　');
        }
        foreach ($arr as $key => $val) {
            $str = preg_replace('/(^'.$val.')|('.$val.'$)/', '', $str);
        }

        return $str;
    }
}

//读取文件内容
if (!function_exists('pcftxt')) 
{
    function pcftxt($pcfurl , $type = 1)
    {
        if(file_exists($pcfurl)) {
            $fp = fopen($pcfurl, 'r');
            $content = fread($fp, filesize($pcfurl));
            fclose($fp);
            if($type){
                $ver = $content ? $content : "";
                $str_encoding = mb_convert_encoding($ver, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');
                $ver1 = explode("\r\n", $str_encoding);             
            }else{
                $ver1 = $content ? $content : "";
            }
        } else {
            $ver1 = "";
        }
        return $ver1;
    }
}
if (!function_exists('getPluginVersion')) 
{
    /**
     * 获取当前插件版本号
     * @param string $ocde 插件标识
     * @return string
     */
    function getPluginVersion($code)
    {
        $ver = 'v1.0.0';
        $config_path = PLUGINS_PATH.$code.'/config.php';
        if (file_exists($config_path)) {
            $config = include $config_path;
            $ver    = !empty($config['version']) ? $config['version'] : $ver;
        } else {
            echo $code . "插件缺少" . $config_path . "配置文件";
        }
        return $ver;
    }
}
if (!function_exists('serverIP')) 
{  
    // 服务器端IP
    function serverIP(){   
        return gethostbyname($_SERVER["SERVER_NAME"]);   
    }  
}
/**
 * 递归创建目录 
 * @param string $path 目录路径，不带反斜杠
 * @param intval $purview 目录权限码
 */
if (!function_exists('tp_mkdir')) 
{
    function tp_mkdir($path, $purview = 0777)
    {
        if (!is_dir($path)) {
            tp_mkdir(dirname($path), $purview);
            if (!mkdir($path, $purview)) {
                return false;
            }
        }
        return true;
    }
}
if (!function_exists('replace_path')) 
{
    /**
     * 将路径斜杆、反斜杠替换为冒号符，适用于IIS服务器在URL上的双重转义限制
     * @param string $filepath 相对路径
     * @param string $replacement 目标字符
     * @param boolean $is_back false为替换，true为还原
     */
    function replace_path($filepath = '', $replacement = ':', $is_back = false)
    {
        if (false == $is_back) {
            $filepath = str_replace(DIRECTORY_SEPARATOR, $replacement, $filepath);
            $filepath = preg_replace('#\/#', $replacement, $filepath);
        } else {
            $filepath = preg_replace('#'.$replacement.'#', '/', $filepath);
            $filepath = str_replace('//', ':/', $filepath);
        }
        return $filepath;
    }
}
if (!function_exists('newisMobile')) 
{
    // 验证手机号码
    function newisMobile($mobile)
    {
        if (preg_match("/^1[3456789]{1}\d{9}$/", $mobile)) {
            return true;
        } else {
            return false;
        }
    }
}
if (!function_exists('isEmail')) 
{
    // 验证邮箱
    function isEmail($email)
    {
        $pattern = '/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i';
        if (preg_match($pattern, $email)) {
            return true;
        } else {
            return false;
        }
    }
}


if (!function_exists('write_global_params')) 
{
    /**
     * 写入全局内置参数
     * @return array
     */
    function write_global_params($options = null)
    {
        $pcfglobal = config('global');
        $webConfigParams = Db::name('config')->where(['inc_type'=> 'web'])->select()->toArray();
        if (!empty($webConfigParams)) {
            $rtn = [];
            foreach ($webConfigParams as $k => $v) {
                $rtn[$v['name']] = $v;
            }
            $webConfigParams = $rtn;
        }
        $web_basehost = !empty($webConfigParams['web_basehost']) ? $webConfigParams['web_basehost']['value'] : '';//网站根网址
        $web_cmspath = !empty($webConfigParams['web_cmspath']) ? $webConfigParams['web_cmspath']['value'] : '';//安装目录
        //启用绝对网址，开启此项后附件、栏目连接、arclist内容等都使用http路径
        $web_multi_site = !empty($webConfigParams['web_multi_site']) ? $webConfigParams['web_multi_site']['value'] : '';
        if($web_multi_site == 1){
            $web_mainsite = $web_basehost.$web_cmspath;
        }else{
            $web_mainsite = '';
        }
        //CMS安装目录的网址
        $param['web_cmsurl'] = $web_mainsite;
        $param['web_templets_dir'] = '/template/'.$pcfglobal['admin_config']['tpl_theme']; // 前台模板根目录
        $param['web_templeturl'] = $web_mainsite.$param['web_templets_dir']; // 前台模板根目录的网址
        $param['web_templets_pc'] = $web_mainsite.$param['web_templets_dir'].'/pc'; // 前台PC模板主题
        $param['web_templets_m'] = $web_mainsite.$param['web_templets_dir'].'/mobile'; // 前台手机模板主题
        $param['web_pcfcms'] = str_replace('#', '', '#h#t#t#p#:#/#/#w#w#w#.#p#c#f#c#m#s#.#c#o#m#'); //网址
        //将内置的全局变量(页面上没有入口更改的全局变量)存储到web版块里
        $inc_type = 'web';
        foreach ($param as $key => $val) {
            if (preg_match("/^".$inc_type."_(.)+/i", $key) !== 1) {
                $nowKey = strtolower($inc_type.'_'.$key);
                $param[$nowKey] = $val;
            }
        }
        sysConfig($inc_type, $param, $options);
    }
}

if (!function_exists('respose')) 
{
    /**
     * 参数 is_jsonp 为true，表示跨域ajax请求的返回值
     * @param string $res 数组
     * @param bool $is_jsonp 是否跨域
     * @return string
     */
    function respose($res, $is_jsonp = false){
        if (true === $is_jsonp) {
            halt(input('callback')."(".json_encode($res).")");
        } else {
            halt(json_encode($res));
        }
    }
}


if (!function_exists('group_same_key')) 
{ 
    /**
     * 将二维数组以元素的某个值作为键，并归类数组
     * array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') )
     * array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') ))
     * @param $arr 数组
     * @param $key 分组值的key
     * @param $count 每个子数组最多个数 为0或者为空表示不限制个数
     * @return array
     */
    function group_same_key($arr,$key,$count = 0){
        $new_arr = array();
        foreach($arr as $k=>$v ){
            if (empty($count) || count($new_arr[$v[$key]]) < $count ){
                $new_arr[$v[$key]][] = $v;
            }
        }
        return $new_arr;
    }
}
if (!function_exists('array_unset_tt')) 
{ 
    //去重复数组
    function array_unset_tt($arr,$key='id'){
        //建立一个目标数组
        $res = array();
        foreach ($arr as $value) {
            //查看有没有重复项
            if(isset($res[$value[$key]])){
                unset($value[$key]);  //有：销毁
            }else{
                $res[$value[$key]] = $value;
            }
        }
        return $res;
    }
}



// 生成一个随机字符 
if (!function_exists('dd2char'))
{
    function dd2char($ddnum)
    {
        $ddnum = strval($ddnum);
        $slen = strlen($ddnum);
        $okdd = '';
        $nn = '';
        for($i=0;$i<$slen;$i++)
        {
            if(isset($ddnum[$i+1]))
            {
                $n = $ddnum[$i].$ddnum[$i+1];
                if( ($n>96 && $n<123) || ($n>64 && $n<91) )
                {
                    $okdd .= chr($n);
                    $i++;
                }
                else
                {
                    $okdd .= $ddnum[$i];
                }
            }
            else
            {
                $okdd .= $ddnum[$i];
            }
        }
        return $okdd;
    }
}


if (!function_exists('get_controller_byct')) 
{
    /**
     * 根据模型ID获取控制器的名称
     * @return mixed
     */
    function get_controller_byct($current_channel)
    {
        $Channeltype = new \app\common\model\ChannelType;
        $channeltype_info = $Channeltype->getInfo($current_channel);
        return $channeltype_info['ctl_name'];
    }
}
if (!function_exists('thumb_img')) 
{
    /**
     * 缩略图 从原始图来处理出来
     * @param type $original_img  图片路径
     * @param type $width     生成缩略图的宽度
     * @param type $height    生成缩略图的高度
     * @param type $thumb_mode    生成方式
     */
    function thumb_img($original_img = '', $width = '', $height = '', $thumb_mode = '')
    {
        // 缩略图配置
        static $thumbConfig = null;
        null === $thumbConfig && $thumbConfig = sysConfig('thumb');
        $thumbextra = config('global.thumb');
        if (!empty($width) || !empty($height) || !empty($thumb_mode)) { 
            // 单独在模板里调用，不受缩略图全局开关影响
        } else { 
            // 非单独模板调用，比如内置的arclist\list标签里
            if (empty($thumbConfig['thumb_open'])) {
                return $original_img;
            }
        }

        // 缩略图优先级别高于七牛云，自动把七牛云的图片路径转为本地图片路径，并且进行缩略图
        //$original_img = is_local_images($original_img);

        // 未开启缩略图，或远程图片
        if (is_http_url($original_img) || stristr($original_img, '/common/images/not_adv.jpg')) {
            return $original_img;
        } else if (empty($original_img)) {
            return '/common/images/not_adv.jpg';
        }
        // 图片文件名
        $filename = '';
        $imgArr = explode('/', $original_img);    
        $imgArr = end($imgArr);
        $filename = preg_replace("/\.([^\.]+)$/i", "", $imgArr);
        $file_ext = preg_replace("/^(.*)\.([^\.]+)$/i", "$2", $imgArr);
        // 如果图片参数是缩略图，则直接获取到原图，并进行缩略处理
        if (preg_match('/\/uploads\/thumb\/\d{1,}_\d{1,}\//i', $original_img)) {
            $pattern = root_path().'public/uploads/allimg/*/'.$filename;
            if (in_array(strtolower($file_ext), ['jpg','jpeg'])) {
                $pattern .= '.jp*g';
            } else {
                $pattern .= '.'.$file_ext;
            }
            $original_img_tmp = glob($pattern);
            if (!empty($original_img_tmp)) {
                $original_img = '/'.current($original_img_tmp);
            }
        } else {
            if ('bmp' == $file_ext && version_compare(PHP_VERSION,'7.2.0','<')) {
                return $original_img;
            }
        }
        $original_img1 = preg_replace('#^#i', '', handle_subdir_pic($original_img));
        $original_img1 = '.' . $original_img1; // 相对路径
        //获取图像信息
        $info = @getimagesize($original_img1);
        //检测图像合法性
        if (false === $info || (IMAGETYPE_GIF === $info[2] && empty($info['bits']))) {
            return $original_img;
        } else {
            if (!empty($info['mime']) && stristr($info['mime'], 'bmp') && version_compare(PHP_VERSION,'7.2.0','<')) {
                return $original_img;
            }
        }
        // 缩略图宽高度
        empty($width) && $width = !empty($thumbConfig['thumb_width']) ? $thumbConfig['thumb_width'] : $thumbextra['width'];
        empty($height) && $height = !empty($thumbConfig['thumb_height']) ? $thumbConfig['thumb_height'] : $thumbextra['height'];
        $width = intval($width);
        $height = intval($height);
        //判断缩略图是否存在
        $path = "uploads/thumb/{$width}_{$height}/";
        $img_thumb_name = "{$filename}";
        // 已经生成过这个比例的图片就直接返回了
        if (is_file($path . $img_thumb_name . '.jpg')) return '/' . $path . $img_thumb_name . '.jpg';
        if (is_file($path . $img_thumb_name . '.jpeg')) return '/' . $path . $img_thumb_name . '.jpeg';
        if (is_file($path . $img_thumb_name . '.gif')) return '/' . $path . $img_thumb_name . '.gif';
        if (is_file($path . $img_thumb_name . '.png')) return '/' . $path . $img_thumb_name . '.png';
        if (is_file($path . $img_thumb_name . '.bmp')) return '/' . $path . $img_thumb_name . '.bmp';
        if (!is_file($original_img1)) {
            return '/common/images/not_adv.jpg';
        }
        try {
            $image = \think\Image::open($original_img1);
            $img_thumb_name = $img_thumb_name.'.'.$image->type();
            // 生成缩略图
            !is_dir($path) && mkdir($path, 0777, true);
            // 填充颜色
            $thumb_color = !empty($thumbConfig['thumb_color']) ? $thumbConfig['thumb_color'] : $thumbextra['color'];
            if (!empty($thumb_mode)) {
                $thumb_mode = intval($thumb_mode);
            } else {
                $thumb_mode = !empty($thumbConfig['thumb_mode']) ? $thumbConfig['thumb_mode'] : $thumbextra['mode'];
            }
            1 == $thumb_mode && $thumb_mode = 6; // 按照固定比例拉伸
            2 == $thumb_mode && $thumb_mode = 2; // 填充空白
            if (3 == $thumb_mode) {
                $img_width = $image->width();
                $img_height = $image->height();
                if ($width < $img_width && $height < $img_height) {
                    // 先进行缩略图等比例缩放类型，取出宽高中最小的属性值
                    $min_width = ($img_width < $img_height) ? $img_width : 0;
                    $min_height = ($img_width > $img_height) ? $img_height : 0;
                    if ($min_width > $width || $min_height > $height) {
                        if (0 < intval($min_width)) {
                            $scale = $min_width / min($width, $height);
                        } else if (0 < intval($min_height)) {
                            $scale = $min_height / $height;
                        } else {
                            $scale = $min_width / $width;
                        }
                        $s_width  = $img_width / $scale;
                        $s_height = $img_height / $scale;
                        //按照原图的比例生成一个最大为$width*$height的缩略图并保存
                        $image->thumb($s_width, $s_height, 1, $thumb_color)->save($path.$img_thumb_name, NULL, 100); 
                    }
                }
                $thumb_mode = 3; // 截减
            }
            //按照原图的比例生成一个最大为$width*$height的缩略图并保存
            $image->thumb($width, $height, $thumb_mode, $thumb_color)->save($path . $img_thumb_name, NULL, 100); 

            //图片水印处理
            $water = sysConfig('water');
            if($water['is_mark']==1 && $water['is_thumb_mark'] == 1 && $image->width()>$water['mark_width'] && $image->height()>$water['mark_height']){
                $imgresource = './' . $path . $img_thumb_name;
                if($water['mark_type'] == 'text'){
                    $ttf = WWW_ROOT.'public/common/font/hgzb.ttf';
                    if (file_exists($ttf)) {
                        $size = $water['mark_txt_size'] ? $water['mark_txt_size'] : 30;
                        $color = $water['mark_txt_color'] ? $water['mark_txt_color'] : '#000000';
                        if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
                            $color = '#000000';
                        }
                        $transparency = intval((100 - $water['mark_degree']) * (127/100));
                        $color.= dechex($transparency);
                        $image->open($imgresource)->text($water['mark_txt'], $ttf, $size, $color, $water['mark_sel'])->save($imgresource);
                        $return_data['mark_txt'] = $water['mark_txt'];
                    }
                }else{
                    $water['mark_img'] = preg_replace('#^(/[/\w]+)?(/public/uploads/|/uploads/)#i', '$2', $water['mark_img']); // 支持子目录
                    $waterPath = public_path().$water['mark_img'];
                    $waterPath = str_replace("\/", "/", $waterPath);
                    if (pcfPreventShell($waterPath) && file_exists($waterPath)) {
                        $quality = $water['mark_quality'] ? $water['mark_quality'] : 80;
                        $waterTempPath = dirname($waterPath).'/temp_'.basename($waterPath);
                        $image->open($waterPath)->save($waterTempPath, null, $quality);
                        $image->open($imgresource)->water($waterTempPath, $water['mark_sel'], $water['mark_degree'])->save($imgresource);
                        @unlink($waterTempPath);
                    }
                }
            }
            
            $img_url = './'.$path.$img_thumb_name;
            return $img_url;
        } catch (think\Exception $e) {
            return $original_img;
        }
    }
}
if (!function_exists('is_local_images')) 
{
    /**
     * 判断远程链接是否属于本地图片，并返回本地图片路径
     * @param string $pic_url 图片地址
     * @param boolean $returnbool 返回类型，false 返回图片路径，true 返回布尔值
     */
    function is_local_images($pic_url = '', $returnbool = false)
    {
        $picPath  = parse_url($pic_url, PHP_URL_PATH);
        if (!empty($picPath) && file_exists('.'.$picPath)) {
            $picPath = preg_replace('#^/#i', '/', $picPath);
            $pic_url = $picPath;
            if (true == $returnbool) {
                return $pic_url;
            }
        }
        if (true == $returnbool) {
            return false;
        } else {
            return $pic_url;
        }
    }
}




if (!function_exists('arctype_options'))
{
    //过滤和排序所有文章栏目，返回一个带有缩进级别的数组
    function arctype_options($spec_id, $arr, $id_alias, $pid_alias)
    {
        $cat_options = array();
        if (isset($cat_options[$spec_id])){
            return $cat_options[$spec_id];
        }
        if (!isset($cat_options[0]))
        {
            $level = $last_id = 0;
            $options = $id_array = $level_array = array();
            while (!empty($arr))
            {
                foreach ($arr AS $key => $value)
                {
                    $id = $value[$id_alias];
                    if ($level == 0 && $last_id == 0)
                    {
                        if ($value[$pid_alias] > 0){
                            break;
                        }
                        $options[$id]          = $value;
                        $options[$id]['level'] = $level;
                        $options[$id][$id_alias]    = $id;
                        unset($arr[$key]);
                        if ($value['has_children'] == 0){
                            continue;
                        }
                        $last_id  = $id;
                        $id_array = array($id);
                        $level_array[$last_id] = ++$level;
                        continue;
                    }
                    if ($value[$pid_alias] == $last_id)
                    {
                        $options[$id]          = $value;
                        $options[$id]['level'] = $level;
                        $options[$id][$id_alias]    = $id;
                        unset($arr[$key]);
                        if ($value['has_children'] > 0)
                        {
                            if (end($id_array) != $last_id){
                                $id_array[] = $last_id;
                            }
                            $last_id    = $id;
                            $id_array[] = $id;
                            $level_array[$last_id] = ++$level;
                        }
                    }
                    elseif ($value[$pid_alias] > $last_id){
                        break;
                    }
                }
                $count = count($id_array);
                if ($count > 1){
                    $last_id = array_pop($id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_id != end($id_array)){
                        $last_id = end($id_array);
                    }else{
                        $level = 0;
                        $last_id = 0;
                        $id_array = array();
                        continue;
                    }
                }
                if ($last_id && isset($level_array[$last_id])){
                    $level = $level_array[$last_id];
                }else{
                    $level = 0;
                    break;
                }
            }
            $cat_options[0] = $options;
        }else{
            $options = $cat_options[0];
        }
        if (!$spec_id){
            return $options;
        }else{
            if (empty($options[$spec_id]))
            {
                return array();
            }
            $spec_id_level = $options[$spec_id]['level'];
            foreach ($options AS $key => $value)
            {
                if ($key != $spec_id){
                    unset($options[$key]);
                }else{
                    break;
                }
            }
            $spec_id_array = array();
            foreach ($options AS $key => $value)
            {
                if (($spec_id_level == $value['level'] && $value[$id_alias] != $spec_id) ||
                    ($spec_id_level > $value['level'])){
                    break;
                }else{
                    $spec_id_array[$key] = $value;
                }
            }
            $cat_options[$spec_id] = $spec_id_array;
            return $spec_id_array;
        }
    }
}
if (!function_exists('get_arr_column'))
{
    /**
     * 获取数组中的某一列
     * @param array $arr 数组
     * @param string $key_name  列名
     * @return array  返回那一列的数组
     */
    function get_arr_column($arr, $key_name)
    {
        if (function_exists('array_column')) {
            return array_column($arr, $key_name);
        }
        $arr2 = array();
        foreach($arr as $key => $val){
            $arr2[] = $val[$key_name];        
        }
        return $arr2;
    }
}

if (!function_exists('view_logic'))
{
    /**
     * 模型对应逻辑
     * @param intval $aid 文档ID
     * @param intval $channel 栏目ID
     * @param intval $result 数组
     * @param mix $allAttrInfo 附加表数据
     * @return array
     */
    function view_logic($aid, $channel, $result = array(), $allAttrInfo = array())
    {
        $allAttrInfo_bool = $allAttrInfo;
        $result['image_list'] = $result['attr_list'] = $result['file_list'] = array();
        return $result;
    }
}